package com.yunshang.ys.ys;



import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * Created by Fengyi on 2016/8/9.
 */
public abstract class YSSubscriber<E> extends Subscriber<YSHttpResult> {


    public abstract void onSuccess(E t,String msg);

    public abstract void onFail(String msg);


    @Override
    public void onStart() {

    }

    @Override
    public void onCompleted() {

    }

    public void onSessionExpire() {
        if (YSConstants.APPLICATION_CONTEXT != null)
            ((YSApplication) YSConstants.APPLICATION_CONTEXT).userLoginExpire();
    }

    @Override
    public void onError(Throwable e) {
        if (YSConstants.IS_DEBUG) {
            e.printStackTrace();
        }
        if (e instanceof HttpException) {
            HttpException exception = (HttpException) e;
            onFail(exception.message());
        } else {
            if (YSConstants.IS_DEBUG) {
                onFail(e.getMessage());
                e.printStackTrace();
            } else
                onFail("发生未知错误，请重试");
        }
    }

    @Override
    public void onNext(YSHttpResult YSHttpResult) {
//        if ("true".equals(YSHttpResult.getCode())) {
        if (YSHttpResult.isCode()) {
            if (YSHttpResult.getData() != null)
                onSuccess((E) YSHttpResult.getData(),YSHttpResult.getMsg());
            else onSuccess(null,YSHttpResult.getMsg());
//        } else if ("false".equals(YSHttpResult.getCode()) ){
        } else if (YSHttpResult.isCode() ){
            onFail(YSHttpResult.getMsg());
        } else {
            onSessionExpire();
        }
    }
}
